package com.jugheadzhou.auth.util;

import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;

public class JWTUtils {

    public static long EXPIRATION_TIME = 1 * 24 * 3600 * 1000;

    public static final SignatureAlgorithm DEFAULT_ALGORITHM = SignatureAlgorithm.HS512;

    public static final String DEFAULT_SECRET = "mz-admin-secret";

    public static final String TOKEN_PREFIX = "Bearer ";

    public static final String CLAIM_EXPIRATION_TIME = "exp";

    public static String createToken(Map<String, Object> claims) {
        return JWTUtils.createToken(null, null, claims, EXPIRATION_TIME);
    }

    public static String createToken(SignatureAlgorithm signAlgorithm, String secretKey, Map<String, Object> claims, long effetiveMs) {

        String jwt = Jwts.builder()
                .setClaims(claims == null ? Maps.newHashMap() : claims)
                .setExpiration(new Date(System.currentTimeMillis() + (effetiveMs <= 0 ? EXPIRATION_TIME : effetiveMs)))
                .signWith(signAlgorithm == null ? DEFAULT_ALGORITHM : signAlgorithm, StringUtils.isEmpty(secretKey) ? DEFAULT_SECRET : secretKey)
                .compact();

        return jwt;
    }

    public static Jws<Claims> parseToken(String token) {
        return JWTUtils.parseToken(null, token);
    }

    public static Jws<Claims> parseToken(String secretKey, String token) {
        return Jwts.parser()
                .setSigningKey(StringUtils.isEmpty(secretKey) ? DEFAULT_SECRET : secretKey)
                .parseClaimsJws(token.replace(TOKEN_PREFIX, ""));
    }

    public static Claims parseTokenAndGetBody(String token) {
        return JWTUtils.parseTokenAndGetBody(null, token);
    }

    public static Claims parseTokenAndGetBody(String secretKey, String token) {
        return Jwts.parser()
                .setSigningKey(StringUtils.isEmpty(secretKey) ? DEFAULT_SECRET : secretKey)
                .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                .getBody();
    }

}
